package com.zx.idc.backend.gui.shiro;

import com.zx.idc.ds.sys.entity.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


/**
 * 用户会话工具类
 *
 * @author rxliuli by 2018/4/19 17:23
 */
@Component
public class TokenManagerUtil {
    /**
     * 日志对象
     */
    protected final Logger logger = LoggerFactory.getLogger(getClass());


    /**
     * 获取当前登陆的系统用户
     *
     * @return 当前登录的用户
     */
    public SysUser getCurrentUser() {
        Object userObject = SecurityUtils.getSubject().getPrincipal();
        if (userObject == null || !(userObject instanceof SysUser)) {
            return null;
        }
        return (SysUser) userObject;
    }

    /**
     * 登录
     */
    public SysUser login(String loginName, String password, Boolean rememberMe, String host, String captcha) {
        SysUsernamePasswordToken token = new SysUsernamePasswordToken(loginName, password, rememberMe, host, captcha);
        SecurityUtils.getSubject().login(token);
        return getCurrentUser();
    }

    /**
     * 判断是否登录
     */
    public boolean isLogin() {
        return SecurityUtils.getSubject().getPrincipal() != null;
    }

    /**
     * 判断是否记住了密码
     */
    public boolean isRemeberMe() {
        return SecurityUtils.getSubject().isRemembered();
    }

    /**
     * 注销当前用户
     */
    public void logout() {
        SecurityUtils.getSubject().logout();
    }

    /**
     * 获取当前 Session(Shiro)
     */
    public Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }


}
